package com.yeskery.nut.bind;

import com.yeskery.nut.annotation.web.*;
import com.yeskery.nut.bind.handler.*;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

/**
 * 注解数据绑定处理器
 * @author sprout
 * 2022-06-11 16:09
 */
public class AnnotationDataBindHandler implements DataBindHandler<Annotation, MethodParamHandler> {

    /** 方法参数处理map */
    private final Map<Class<? extends Annotation>, MethodParamHandler> methodParamHandlerMap = new HashMap<>();

    {
        // 注册RequestBody处理器
        methodParamHandlerMap.put(RequestBody.class, new RequestBodyMethodParamHandler());
        // 注册RequestParam处理器
        methodParamHandlerMap.put(RequestParam.class, new RequestParamMethodParamHandler());
        // 注册CookieValue处理器
        methodParamHandlerMap.put(CookieValue.class, new CookieValueMethodParamHandler());
        // 注册RequestHeader处理器
        methodParamHandlerMap.put(RequestHeader.class, new RequestHeaderMethodParamHandler());
        // 注册RequestAttribute处理器
        methodParamHandlerMap.put(RequestAttribute.class, new RequestAttributeMethodParamHandler());
        // 注册SessionAttribute处理器
        methodParamHandlerMap.put(SessionAttribute.class, new SessionAttributeMethodParamHandler());
        // 注册ServerContextAttribute处理器
        methodParamHandlerMap.put(ServerContextAttribute.class, new ServerContextAttributeMethodParamHandler());
        // 注册PathVariable处理器
        methodParamHandlerMap.put(PathVariable.class, new PathVariableMethodParamHandler());
    }

    /**
     * 根据注解对象获取方法参数对象的处理接口
     * @param data 注解对象
     * @return 方法参数对象的处理接口
     */
    @Override
    public MethodParamHandler handle(Annotation data) {
        for (Map.Entry<Class<? extends Annotation>, MethodParamHandler> entry : methodParamHandlerMap.entrySet()) {
            if (entry.getKey().isAssignableFrom(data.getClass())) {
                return entry.getValue();
            }
        }
        return null;
    }
}
